//
//  JKReporter.m
//  app
//
//  Created by 王少宁 on 15/4/24.
//  Copyright (c) 2015年 hdaren. All rights reserved.
//

#import "JKReporter.h"
#import "JKHttpClient.h"
#import <sys/sysctl.h>

//keychian
#define KEY_CHAIN_UDID [SvUDIDTools UDID]
//当前版本号
#define APP_VERSION [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"]

@interface JKReporter ()
@property (nonatomic, retain) JKHttpClient * http;
@property (nonatomic, retain) SNUniteUrl * uniteUrl;
@end

@implementation JKReporter

+ (id)sharedReporter
{
    AS_SINGLETON(JKReporter, reporter, {
        reporter = [[JKReporter alloc] init];
        reporter.uniteUrl = [SNUniteUrl shareUniteUrl];
        reporter.http = [[JKHttpClient alloc] init];
    })
    
    [reporter reportCrashLog];
    
    return reporter;
}

#pragma mark - 上报崩溃日志
- (void)reportCrashLog
{
    NSFileManager * fm = [NSFileManager defaultManager];
    
    if (![fm fileExistsAtPath:kCrashLogFilePath]) {
        return;
    }
    
    NSMutableString * crashLogStr = [[NSMutableString alloc] init];
    
    NSError* err;
    NSString * crashStr = [NSString stringWithContentsOfFile:kCrashLogFilePath encoding:NSUTF8StringEncoding error:&err];
    [crashLogStr appendString:crashStr];
    
    [crashLogStr appendString:[NSString stringWithFormat:@"\nIMEI=%@",KEY_CHAIN_UDID]];
    [crashLogStr appendString:[NSString stringWithFormat:@"\nMAC=%@",KEY_CHAIN_UDID]];
    [crashLogStr appendString:[NSString stringWithFormat:@"\n型号=%@",[self currentDevice]]];
    [crashLogStr appendString:[NSString stringWithFormat:@"\n型号=%@",[self currentDevice]]];
    [crashLogStr appendString:[NSString stringWithFormat:@"\n系统=%@",[[UIDevice currentDevice] systemVersion]]];
    [crashLogStr appendString:[NSString stringWithFormat:@"\n设备ID=%@",KEY_CHAIN_UDID]];
    [crashLogStr appendString:[NSString stringWithFormat:@"\n当前版本名=%@",APP_VERSION]];
    [crashLogStr appendString:[NSString stringWithFormat:@"\n当前版本号=%@",APP_VERSION]];
    
    NSDictionary * parm = @{@"data":crashLogStr};
    [self.http post:self.uniteUrl.log_crashLogReportUrl params:parm result:^(JKResponse *resp) {
        
//        if (resp.success) {
//            DLog(@"上报成功");
//        } else {
//            DLog(@"上报失败 : %@",resp.error);
//        }
        
    }];
        
    NSFileManager * fileManager = [NSFileManager defaultManager];
    [fileManager removeItemAtPath:kCrashLogFilePath error:&err];
}

#pragma mark - 判断当前版本
- (NSString *)currentDevice
{
    size_t size;
    sysctlbyname ("hw.machine" , NULL , &size ,NULL ,0);
    char *model = (char *)malloc(size);
    sysctlbyname ("hw.machine" , model , &size ,NULL ,0);
    NSString * strModel3 = [NSString stringWithCString: model encoding:NSUTF8StringEncoding];
    free(model);
    return strModel3;
}

@end
